package DAO;
 
import Database.DBConnection;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import Model.Noticia;
import Util.PropertiesManager;
import DAO.UsuarioDAO;
import java.util.logging.Level;
import java.util.logging.Logger;
import Model.Usuario;
 
/**
 *
 * @author karenborges
 */
public class NoticiaDAO implements InterfaceDAO{
     
    private HashMap dados;
     
    public NoticiaDAO() throws IOException{
        dados = new PropertiesManager("sql.properties").readPropertiesFile();
    }
 
    @Override
    public void inserir(Object obj) throws SQLException {
        Noticia news = (Noticia) obj;
         
        Connection conexao = DBConnection.getInstance();
        String sql = (String) dados.get("Insert.Noticia");
        PreparedStatement pstmt = conexao.prepareStatement(sql);
        pstmt.setInt(1, news.getUsuario().getId());
        pstmt.setString(2, news.getTitulo());
        pstmt.setString(3, news.getDescricao());
        pstmt.setString(4, news.getLink());
        pstmt.setString(5, news.getData());
        int rs = pstmt.executeUpdate();
        pstmt.close();
    }
 
    @Override
    public void excluir(Object obj) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
 
    @Override
    public ArrayList pesquisarTudo() throws SQLException {
         ArrayList newsList = new ArrayList();
        Connection conexao = DBConnection.getInstance();
        String sql = (String) dados.get("SelectAll.Noticia");
        PreparedStatement pstmt = conexao.prepareStatement(sql);
 
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            Noticia news = new Noticia();
            news.setId(rs.getInt(1));
            news.setTitulo(rs.getString(3));
            news.setDescricao(rs.getString(4));
            news.setLink(rs.getString(5));
            news.setData(rs.getString(6));
 
            int id = (rs.getInt(2));
            try {
               Usuario user = (Usuario) (new UsuarioDAO().pesquisarChave(id));
                           news.setUsuario(user);
            } catch (IOException ex) {
                Logger.getLogger(NoticiaDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
 
            newsList.add(news);
        }
        pstmt.close();
        return newsList;
    }
 
    @Override
    public Object pesquisarChave(int chave) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
 
    @Override
    public void editar(Object obj) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
     
}